import services from '@/services/backup';
import sshServices from '@/services/ssh';
import {ActionType, PageContainer, ProColumns, ProTable,} from '@ant-design/pro-components';
import {Button, Dropdown, message, Modal} from 'antd';
import React, {useEffect, useRef, useState} from 'react';
import CreateForm from '@/components/CreateForm';
import {useNavigate} from 'umi';
import EditForm, {FormValueType} from './components/EditForm';
import {DownOutlined} from '@ant-design/icons';

const { page, append, deleteByIds,dbTypes, edit, backup} = services.DbBackupController;


/**
 * 新增数据库备份
 * @param fields
 */
const handleAdd = async (fields: API.DbBackupAdd) => {
    const hide = message.loading('正在添加');
    try {
        // console.log("addFields:", fields)
        await append(fields);
        hide();
        message.success('添加成功');
        return true;
    } catch (error) {
        hide();
        // message.error('添加失败请重试！');
        return false;
    }
};

/**
 *  删除数据库备份
 * @param id
 */
const handleRemove = async (id: number) => {
    const hide = message.loading('正在删除');
    if (!id) return true;
    try {
        await deleteByIds([id]);
        hide();
        message.success('删除成功');
        return true;
    } catch (error) {
        hide();
        //   message.error('删除失败，请重试');
        return false;
    }
};


/**
 * 编辑数据库备份
 * @param fields
 */
const handleUpdate = async (fields: FormValueType) => {
    const hide = message.loading('正在编辑');
    try {
        console.log("fields:", fields)
        await edit({...fields} as API.DbBackupEdit);
        hide();
        message.success('编辑成功');
        return true;
    } catch (error) {
        hide();
        // message.error('添加失败请重试！');
        return false;
    }
};



/**
 * 备份
 * @param fields
 */
const handleBackUp = async (id: number) => {
  const hide = message.loading('正在备份,请稍后...', 0);
  try {
      const resp = await backup(id);
      hide();
      message.success(resp.message);
      return true;
  } catch (error) {
      hide();
      // message.error('添加失败请重试！');
      return false;
  }
};


const TableList: React.FC<unknown> = () => {
    const actionRef = useRef<ActionType>();
    const [editModalVisible, handleEditModalVisible] = useState<boolean>(false);
    const [stepFormValues, setStepFormValues] = useState({});
    // 字典
    const [dictTypeEnumData, setDictTypeEnumData] = useState({});
    // 分页
    const [current, setCurrent] = useState(1); // 当前页码
    const [pageSize, setPageSize] = useState(10); // 每页显示条数
    // 新增
    const [createModalVisible, handleModalVisible] = useState<boolean>(false);
    // ssh
    const [sshData, setSshData] = useState({});
    const navigate = useNavigate();

    // 初始化数据
    useEffect(() => {
      fetchSSH();
      fetchValueEnumData();
    }, []);


  /**
   * 获取ssh数据
   */
  async function fetchSSH() {
    const response = await sshServices.SshInfoController.listSSH();
    if (response && Array.isArray(response.data)) {
      const dictData = response.data;
      const valueEnumMap: Record<string, { text: string; status: number }> = {};
      dictData.reduce((acc , item ) => {
        acc[item.id] =  { text: item.name , status: item.id };
        return acc;
      }, valueEnumMap);
      setSshData(valueEnumMap);
    }
  }

    // 字典类型枚举数据
    async function fetchValueEnumData() {
      const response = await dbTypes();
      if (response && Array.isArray(response.data)) {
        const dictData = response.data;
        const valueEnumMap: Record<string, { text: string; status: string }> = {};
        // 将字典数据转换为valueEnum格式
        dictData.reduce((acc: { [x: string]: { text: any; status: any; }; }, item: { type: string; name: string; }) => {
          acc[item.name] =  { text: item.type , status: item.name };
          return acc;
        }, valueEnumMap);
        setDictTypeEnumData(valueEnumMap);
      }
    }

      // 列表数据接口
    const columns: ProColumns<API.DbBackup>[] = [
        {
            title: 'id',
            dataIndex: 'id',
            tooltip: '唯一的 key',
            hideInForm: true,
            hideInTable: true,
            search: false
        },
        {
            title: '连接名',
            dataIndex: 'name',
            valueType: 'text',
            formItemProps: {
                rules: [{required: true, message: '请输入连接名'}],
            },
        },
        {
          title: '数据库IP',
          dataIndex: 'host',
          valueType: 'text',
          search: false,
          formItemProps: {
              rules: [{required: true, message: '请输入数据库IP'}],
          },
        },
        {
            title: '数据库账户',
            dataIndex: 'user',
            valueType: 'text',
            copyable: true,
            search: false,
            formItemProps: {
                rules: [{required: true, message: '请输入数据库账户'}],
            },
        },
        {
            title: '数据库密码',
            dataIndex: 'password',
            valueType: 'password',
            ellipsis: true, // 启用文本省略
            copyable: true,
            search: false,
            formItemProps: {
                rules: [{required: true, message: '请输入数据库密码'}],
            },
        },
        {
            title: '数据库端口',
            dataIndex: 'port',
            valueType: 'digit',
            search: false,
            initialValue: 3306,
            tooltip:"常规默认都是3306端口",
            formItemProps: {
                rules: [{required: true, message: '请输入数据库端口'}],
            },
        },
        {
            title: '数据库名',
            dataIndex: 'dbName',
            valueType: 'text',
            search: false,
            formItemProps: {
              rules: [{required: true, message: '请输入数据库名'}],
          },
        },
        {
          title: 'dump命令地址',
          dataIndex: 'dumpPath',
          valueType: 'text',
          initialValue: '/usr/bin/mysqldump',
          tooltip: '如果服务器上没有安装mysql客户端，需要手动指定mysqldump命令的路径,通过 which mysqldump 查询[docker的话格式为docker exec mysql /usr/bin/mysqldump]',
          search: false,
          copyable: true,
          formItemProps: {
            rules: [{required: true, message: '请输入dump命令地址'}],
        },
      },
      {
        title: '备份存储地址',
        dataIndex: 'remoteBackupPath',
        initialValue: '/path/to/remote/backup/',
        tooltip: '远程服务器上的地址',
        valueType: 'text',
        search: false,
        copyable: true,
        formItemProps: {
          rules: [{required: true, message: '请输入备份存储地址'}],
        },
      },
      {
        title: '数据库类型',
        dataIndex: 'dbType',
        valueEnum: dictTypeEnumData,
        formItemProps: {
          rules: [{required: true, message: '请输入数据库类型'}],
        },
      },
      {
        title: 'ssh',
        dataIndex: 'sshId',
        valueType: 'text',
        tooltip: '根据这个进行备份的',
        valueEnum: sshData,
        search: false,
        formItemProps: {
          rules: [{required: true, message: '请输入sshId'}],
        },
      },
      {
          title: '操作',
          dataIndex: 'option',
          valueType: 'option',
          render: (_, record) => {
            const menuItems = [
              {
                key: 'delete',
                label: '删除',
                onClick: () => {
                  Modal.confirm({
                    title: '确认删除',
                    content: (
                      <span>
                        确定要删除任务
                        <span style={{ fontWeight: 'bold', color: 'red' }}>
                          {record.name}
                        </span>
                        吗？
                      </span>
                    ),
                    okText: '确认',
                    okType: 'danger',
                    cancelText: '取消',
                    onOk: async () => {
                      const success = await handleRemove(record.id);
                      if (success) {
                        actionRef.current?.reloadAndRest?.();
                      }
                    },
                  });
                },
              },
              {
                key: 'backup',
                label: record.sshId==null ? null: '手动备份',
                onClick: async () => {
                  handleBackUp(record.id)
                },
              },
              {
                key: 'backupFiles',
                label: '备份文件详情',
                onClick: async () => {
                    const params = new URLSearchParams({
                      name: record.name,
                    });
                    const url = `/backup/files/${record.id}?${params.toString()}`;
                    console.log('Navigating to:', url);
                    navigate(url);
                },
              },
              {
                key: 'edit',
                label: '编辑',
                onClick: () => {
                  handleEditModalVisible(true);
                  setStepFormValues(record);
                },
              },
            ];
            return (
              <Dropdown menu={{ items: menuItems }}>
                <a onClick={(e) => e.preventDefault()}>
                  操作 <DownOutlined />
                </a>
              </Dropdown>
            );

          },
      },
    ];

    return (
        <PageContainer
            header={{
              title: '',
            }}
        >
          <ProTable<API.DbBackup>
              headerTitle=""
              actionRef={actionRef}
              rowKey="id"
              search={{
                labelWidth: 120,
              }}
              toolBarRender={() => [
                <Button
                    key="1"
                    type="primary"
                    onClick={() => handleModalVisible(true)}
                >
                  新增
                </Button>,
              ]}
              pagination={{
                current, // 当前页码
                pageSize, // 每页条数
                showSizeChanger: true, // 是否可以改变 pageSize
            pageSizeOptions: ['5', '10', '20', '50'], // 自定义每页条数下拉选项
            onChange: (page, pageSize) => { // 页码或 pageSize 改变的回调。
              setCurrent(page);
              setPageSize(pageSize);
            },
            onShowSizeChange: (current, size) => {// pageSize 改变的回调。
              setCurrent(current);
              setPageSize(size);
            },
          }}
          // , sorter, filter
          request={async (params) => {
            const find: API.DbBackupPage  = {
              name: params.name,
              dbName: params.dbName,
              dbType: params.dbType,
              page : {
                pageIndex: params.current,
                pageSize: params.pageSize,
              },
            };
            const { data, success } = await page({
              ... find,
              // FIXME: remove @ts-ignore
              // @ts-ignore
              // sorter,
              // filter,
            });
            return {
                data: data?.rows || [],
                total: data?.total,
                pageSize: data?.pageSize,
                current: data?.currentPage,
                success,
            };
          }}
          columns={columns}
        />
        <CreateForm
          onCancel={() => handleModalVisible(false)}
          modalVisible={createModalVisible}
        >
          <ProTable<API.DbBackup, API.DbBackupAdd>
            onSubmit={async (value) => {
              const success = await append(value);
              if (success) {
                handleModalVisible(false);
                if (actionRef.current) {
                  actionRef.current.reload();
                }
              }
            }}
            rowKey="id"
            type="form"
            columns={columns}
          />
        </CreateForm>
        {stepFormValues && Object.keys(stepFormValues).length ? (
        <EditForm
          onSubmit={async (value) => {
            const success = await handleUpdate(value);
            if (success) {
              handleEditModalVisible(false);
              setStepFormValues({});
              if (actionRef.current) {
                actionRef.current.reload();
              }
            }
          }}
          onOpenChange={(visible) => {
            if (!visible) {
              handleEditModalVisible(false);
              setStepFormValues({});
            }
          }}
          editModalVisible={editModalVisible}
          dbTypeEnum={dictTypeEnumData}
          sshData={sshData}
          values={stepFormValues}
        />
      ) : null}
      </PageContainer>
    );
};

export default TableList;
